<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/16
 * Time: 21:00
 */
namespace Pay\Controller;

use Common\Common\Api\Order;
use Common\Common\Api\Ordermember;
use Common\Common\Api\Redis\Channel;
use Common\Common\Api\Redis\Product;

/**
 * Class ManyiController
 * @package Pay\Controller
 */
class A8Controller extends PayController{
    protected $config;
    protected $class;

    public function __construct(){
        parent::__construct();
        $classes = explode("\\", __CLASS__);
        $class = end($classes);
        $this->class = substr($class, 0, stripos($class, "Controller"));
    }

    public function pay($array){
        $this->config = Channel::getInstance()->getById($array['channel']);
        if (!$this->config) {
            $this->showmessage('通道错误!', ['code' => C("THIRDCODES." . $this->class)]);
        }

        $parameter = array(
            'code' => $this->config['code'], // 通道名称
            'title' => $this->config['title'],
            'exchange' => 1, // 金额比例
            'gateway' => $this->config['gateway'],
            'orderid' => createOrderId(),
            'out_trade_id' => I("request.pay_orderid"),
            'body' => 'pay',
            'channel' => $array
        );

        $return = $this->orderadd($parameter);

        $data = array();
        $data['pay_type'] = '3';
        $data['userid'] = $this->config['mch_id'];
        $data['terminal_time'] = date('YmdHis', time());
        $data['req_time'] = date("Ym", time());
        $data['total_fee'] = intval($return['amount'] * 100);
        $data['attach'] = $return['orderid'];
        $data['title'] = 'A8';
        $data['body'] = 'A8';
        $data['notify_url'] = $return['notifyurl'];
        $data['key_sign'] = $this->getSign($data);

        $res = curl_json($this->config['gateway'], $data, 1);

        $res = json_decode($res, true);

        $code = $res['data']['html'];
        if (!$code) {
            if ($res['msg']) {
                $this->showmessage($res['message'], ['code' => C("THIRDCODES." . $this->class)]);
            }
            $this->showmessage('获取支付链接失败!', ['code' => C("THIRDCODES." . $this->class)]);
        }

        echo $code;
    }

    private function getSign($data){
        ksort($data);

        $str = "";
        foreach ($data as $k => $v) {
            if(in_array($k,['key_sign'])){
                continue;
            }

            $str .= "{$k}={$v}&";
        }
        $str = substr($str, 0, -1) . $this->config['signkey'];

        return md5($str);
    }

    //通知
    public function notifyurl(){
        $this->debug_callback();

        $p = file_get_contents("php://input");

        //$p = '{"result_code":"1","result_msg":"支付成功","pay_type":3,"userid":100117,"addtime":1561554846,"end_time":1561554901,"total_fee":50000,"out_trade_no":"20190626211406100117747008","attach":"sn20190626211406720","key_sign":"fc3631d6172cb40ccd0c922cf8fa6fe5"}';

        $p = json_decode($p, true);

        //获取订单信息
        $orderid = $p['attach'];
        $find = $this->checkOrderNotify($orderid);

        //保存回调数据
        M("Order")->where(array("pay_orderid" => $p['busi_order_no']))->save(array(
            "pay_orderid_rd" => htmlspecialchars($p['transaction_id'])));

        //获取渠道信息
        $this->config = M("Channel")->where(array('code' => $this->class))->find();

        $ReturnArray = array( // 返回字段
            "memberid" => $p["memberid"], // 商户ID
            "orderid" => $p["orderid"], // 订单号
            'transaction_id' => $p["transaction_id"],
            "amount" => $p["amount"], // 交易金额
            "datetime" => $p["datetime"], // 交易时间
            "returncode" => $p["returncode"]
        );

        $sign = $p['key_sign'];
        $sign2 = $this->getSign($p);

        if($sign !== $sign2){
            exit("sign wrong");
        }

        if ($p['result_code'] !== '1') {
            exit("pay_fail");
        }

        $this->async($find['pay_orderid'], 'success');
    }

    public function callBackUrl(){
        echo '处理成功';
        exit;
    }
}